//
//  Sky72Facebook.m
//  Sky72
//
//  Created by ladaka on 13. 10. 4..
//  Copyright (c) 2013년 ladaka Inc. All rights reserved.
//

#import "Sky72Facebook.h"
#import "Sky72AppDelegate.h"
#import "Sky72FacebookView.h"

@interface Sky72Facebook ()

@end

@implementation Sky72Facebook
@synthesize loggedInUser = _loggedInUser;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // Facebook custom login view
//    FBCustomLoginView *fbLoginView = [[FBCustomLoginView alloc] init];
    self.fbLoginView.frame = CGRectOffset(self.fbLoginView.frame, 5, 5);
    [self.fbLoginView setBackgroundImage:[UIImage imageNamed:@"a"]];
    self.fbLoginView.label.text = @"SNS 공유하기";
    
    self.fbLoginView.delegate = self;
    
//    [self.view addSubview:fbLoginView];
    [self.fbLoginView sizeToFit];
    
    // 친구 추가하기 탭 인식 설정
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addFriends)];
    tapRecognizer.numberOfTapsRequired = 1;
    [self.tvPostFriend addGestureRecognizer:tapRecognizer];
    
    self.vSubView.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    self.loggedInUser = nil;
    [self setFbLoginView:nil];
    [self setLbTest:nil];
    [self setVSubView:nil];
    [self setVShareView:nil];
    [super viewDidUnload];
}

- (void) call {
    Sky72FacebookView *controller = [[Sky72FacebookView alloc]
                                     initWithNibName:@"Sky72FacebookView" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - FBLoginViewDelegate
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
    // first get the buttons set for login mode
    NSLog(@"%s",__FUNCTION__);
    self.lbTest.text = @"Logged On";
    
//    [self call];
    
    self.vSubView.hidden = NO;
    [self.vSubView addSubview:self.vShareView];
}

- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
                            user:(id<FBGraphUser>)user {
    // here we use helper properties of FBGraphUser to dot-through to first_name and
    // id properties of the json response from the server; alternatively we could use
    // NSDictionary methods such as objectForKey to get values from the my json object
//    self.labelFirstName.text = [NSString stringWithFormat:@"Hello %@!", user.first_name];
    // setting the profileID property of the FBProfilePictureView instance
    // causes the control to fetch and display the profile picture for the user
//    self.profilePic.profileID = user.id;
    self.loggedInUser = user;
    NSLog(@"%s",__FUNCTION__);
}

- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
    // test to see if we can use the share dialog built into the Facebook application
    NSLog(@"%s",__FUNCTION__);
    FBShareDialogParams *p = [[FBShareDialogParams alloc] init];
    p.link = [NSURL URLWithString:@"http://developers.facebook.com/ios"];
#ifdef DEBUG
    [FBSettings enableBetaFeatures:FBBetaFeaturesShareDialog];
#endif
//    BOOL canShareFB = [FBDialogs canPresentShareDialogWithParams:p];
//    BOOL canShareiOS6 = [FBDialogs canPresentOSIntegratedShareDialogWithSession:nil];
//    self.buttonPostStatus.enabled = canShareFB || canShareiOS6;
    
    // "Post Status" available when logged on and potentially when logged off.  Differentiate in the label.
    
    self.loggedInUser = nil;
    self.lbTest.text = @"Logged Off)";
}

- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
    // see https://developers.facebook.com/docs/reference/api/errors/ for general guidance on error handling for Facebook API
    // our policy here is to let the login view handle errors, but to log the results
    
    NSLog(@"%s",__FUNCTION__);
    NSLog(@"FBLoginView encountered an error=%@", error);
}

#pragma mark - Share View UI Behavior
- (void)addFriends {
    //    if (FBSession.activeSession.isOpen) {
    //        FBFriendPickerViewController *friendPicker = [[FBFriendPickerViewController alloc] init];
    //
    //        // Set up the friend picker to sort and display names the same way as the
    //        // iOS Address Book does.
    //
    //        // Need to call ABAddressBookCreate in order for the next two calls to do anything.
    //        ABAddressBookRef addressBook = ABAddressBookCreate();
    //        ABPersonSortOrdering sortOrdering = ABPersonGetSortOrdering();
    //        ABPersonCompositeNameFormat nameFormat = ABPersonGetCompositeNameFormat();
    //
    //        friendPicker.sortOrdering = (sortOrdering == kABPersonSortByFirstName) ? FBFriendSortByFirstName : FBFriendSortByLastName;
    //        friendPicker.displayOrdering = (nameFormat == kABPersonCompositeNameFormatFirstNameFirst) ? FBFriendDisplayByFirstName : FBFriendDisplayByLastName;
    //
    //        [friendPicker loadData];
    //        [friendPicker presentModallyFromViewController:self
    //                                              animated:YES
    //                                               handler:^(FBViewController *sender, BOOL donePressed) {
    //                                                   if (donePressed) {
    //                                                       self.selectedFriends = friendPicker.selection;
    //                                                       [self updateWithFriends];
    //                                                   }
    //                                               }];
    //        CFRelease(addressBook);
    //    } else {
    //        // if not logged in, give the user the option to log in
    //        [self presentLoginSettings];
    //    }
    
    if (FBSession.activeSession.isOpen) {
        FBFriendPickerViewController *friendPickerController = [[FBFriendPickerViewController alloc] init];
        friendPickerController.title = @"Pick Friends";
        [friendPickerController loadData];
        
        // Use the modal wrapper method to display the picker.
        [friendPickerController presentModallyFromViewController:self animated:YES handler:
         ^(FBViewController *sender, BOOL donePressed) {
             
             if (!donePressed) {
                 return;
             }
             
             NSString *message;
             
             if (friendPickerController.selection.count == 0) {
                 message = @"<No Friends Selected>";
             } else {
                 
                 NSMutableString *text = [[NSMutableString alloc] init];
                 
                 self.selectedFriends = friendPickerController.selection;
                 
                 NSMutableArray *arr = [[NSMutableArray alloc] init];
                 
                 // we pick up the users from the selection, and create a string that we use to update the text view
                 // at the bottom of the display; note that self.selection is a property inherited from our base class
                 for (id<FBGraphUser> user in friendPickerController.selection) {
                     if ([text length]) {
                         [text appendString:@", "];
                     }
                     [text appendString:user.name];
//                     [self.arrSelectedFriendId addObject:user.id];
                     [self.arrSelectedFriendId addObject:[NSDictionary dictionaryWithObject:user.id forKey:@"tag_uid"]];
                     NSLog(@"id %@", user.id);
                     NSLog(@"name %@", user.name);
                     
                     [arr addObject:user.id];
                     
                     /*
                      NSMutableArray *arrReservation = [[NSMutableArray alloc] init];
                      [arrReservation addObject:@"정기예약"];
                      [arrReservation addObject:@"빠른예약"];
                      
                      NSMutableDictionary *arrDicList2 = [[NSMutableDictionary alloc]init];
                      [arrDicList2 setObject:arrReservation forKey:@"data"];
                      [arrDicList2 setObject:@"예약하기" forKey:@"section"];
                      [self.arrTableViewList addObject:arrDicList2];
                      */
                 }
//                 [self.arrFriendsId setObject:self.arrSelectedFriendId forKey:@"Friends facebook ID"];
                 NSLog(@"%d", arr.count);
                 message = text;
                 self.tvPostFriend.text = message;
                 
                 self.arrSelectedFriendId = arr;
                 
                 NSLog(@"%d", self.arrSelectedFriendId.count);
                 
//                 [self updateWithFriends];
             }
             
//             [[[UIAlertView alloc] initWithTitle:@"You Picked:"
//                                         message:message
//                                        delegate:nil
//                               cancelButtonTitle:@"OK"
//                               otherButtonTitles:nil]
//              show];
         }];
    } else {
        [self presentLoginSettings];
    }
}
//
//- (void)updateWithFriends {
//    int friendCount = self.selectedFriends.count;
//    if (friendCount > 2) {
//        // Just to mix things up, don't always show the first friend.
//        id<FBGraphUser> randomFriend = [self.selectedFriends objectAtIndex:arc4random() % friendCount];
//        self.tvPostFriend = [NSString stringWithFormat:@"%@ and %d others",
//                             randomFriend.name,
//                             friendCount - 1];
//    } else if (friendCount == 2) {
//        id<FBGraphUser> friend1 = [self.selectedFriends objectAtIndex:0];
//        id<FBGraphUser> friend2 = [self.selectedFriends objectAtIndex:1];
//        self.tvPostFriend = [NSString stringWithFormat:@"%@ and %@",
//                             friend1.name,
//                             friend2.name];
//    } else if (friendCount == 1) {
//        id<FBGraphUser> friend = [self.selectedFriends objectAtIndex:0];
//        self.tvPostFriend.text = friend.name;
//    }
//}

-(void)presentLoginSettings {
    if (self.settingsViewController == nil) {
        self.settingsViewController = [[FBUserSettingsViewController alloc] init];
#ifdef __IPHONE_7_0
        if ([self.settingsViewController respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
            self.settingsViewController.edgesForExtendedLayout &= ~UIRectEdgeTop;
        }
#endif
        self.settingsViewController.delegate = self;
    }
    
    [self.navigationController pushViewController:self.settingsViewController animated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if (touch.phase == UITouchPhaseBegan) {
        if([self.tfPostMessage isFirstResponder]) {
            [self.tfPostMessage resignFirstResponder];
        }
    }
}

#pragma mark - Post Action
- (IBAction)onClickPost:(id)sender {
    if (FBSession.activeSession.isOpen) {
        if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
            [self requestPermissionAndPost];
        } else {
            [self postAction];
        }
    }
}

/*
- (void)postAction {
    NSMutableDictionary *postTest = [[NSMutableDictionary alloc] init];
    [postTest setObject:self.tfPostMessage.text forKey:@"message"];
//    [postTest setObject:@"APPID" forKey:@"app_id"];
//    NSString *userFBID = [NSString stringWithFormat:@"%@", [self.arrFriendsId objectForKey:@"Friends facebook ID"]];
    
//    [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"%@/feed?access_token=%@", userFBID] parameters:postTest HTTPMethod:@"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//        if (error) {
//            [self presentAlertForError:error];
//        }
//    }];

//    [postTest setObject:self.arrSelectedFriendId forKey:@"tag"];
[postTest setObject:@"100001920464554" forKey:@"tag"];
//    [postTest setObject:self.selectedFriends forKey:@"tag"];
    [FBRequestConnection startWithGraphPath:@"me/feed" parameters:postTest HTTPMethod:@"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        if (error) {
            [self presentAlertForError:error];
        } else {
            NSLog(@"success");
        }
    }];
}
 */

- (void) postAction {
    id<Sky72Action> action = (id<Sky72Action>) [FBGraphObject graphObject];
    
    action.tags = self.selectedFriends;
    
    action.message = @"test test";
    
    [FBRequestConnection startForPostWithGraphPath:@"me/feed" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        if (error) {
            [self presentAlertForError:error];
        } else {
            NSLog(@"success");
        }
    }];
}

// Helper method to request publish permissions and post.
- (void)requestPermissionAndPost {
    [FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                          defaultAudience:FBSessionDefaultAudienceFriends
                                        completionHandler:^(FBSession *session, NSError *error) {
                                            if (!error && [FBSession.activeSession.permissions indexOfObject:@"publish_actions"] != NSNotFound) {
                                                // Now have the permission
                                                [self postAction];
                                            } else if (error){
                                                // Facebook SDK * error handling *
                                                // if the operation is not user cancelled
                                                if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
                                                    [self presentAlertForError:error];
                                                }
                                            }
                                        }];
}

- (void) presentAlertForError:(NSError *)error {
    // Facebook SDK * error handling *
    // Error handling is an important part of providing a good user experience.
    // When fberrorShouldNotifyUser is YES, a fberrorUserMessage can be
    // presented as a user-ready message
    if (error.fberrorShouldNotifyUser) {
        // The SDK has a message for the user, surface it.
        [[[UIAlertView alloc] initWithTitle:@"Something Went Wrong"
                                    message:error.fberrorUserMessage
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    } else {
        NSLog(@"unexpected error:%@", error);
    }
}
- (IBAction)onClickLogout:(id)sender {
    if (self.settingsViewController == nil) {
        self.settingsViewController = [[FBUserSettingsViewController alloc] init];
//#ifdef __IPHONE_7_0
//        if ([self.settingsViewController respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
//            self.settingsViewController.edgesForExtendedLayout &= ~UIRectEdgeTop;
//        }
//#endif
        self.settingsViewController.delegate = self;
    }
    
    [self.navigationController pushViewController:self.settingsViewController animated:YES];
}
@end
